package ltd.dujiabao.orderservice.config;

import lombok.extern.slf4j.Slf4j;
import ltd.dujiabao.orderservice.dao.OutboxMessageRepository;
import ltd.dujiabao.orderservice.domain.enums.MessageStatus;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author Bowie Du
 * @date 2025/7/12 15:30
 */
@Slf4j
@Component
public class OutboxMessageCallback implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {

    @Autowired
    private OutboxMessageRepository outboxMessageRepository;

    private static final String ERROR_MES_TEMPLATE = "replyCode: %d, replyText: %s";

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String messageId = correlationData.getId();
        if (ack) {
            log.info("messageId: {} ack", messageId);
            return;
        }
        log.error("messageId: {} nack, cause: {}", messageId, cause);
        outboxMessageRepository.updateStatusAndErrorMsgByMessageId(
                messageId, MessageStatus.FAILED.getValue(), cause, LocalDateTime.now());
    }

    @Override
    public void returnedMessage(ReturnedMessage returned) {
        String messageId = returned.getMessage().getMessageProperties().getMessageId();
        log.error("messageId: {} returned, replyCode:{}, cause: {}",
                messageId, returned.getReplyCode(), returned.getReplyText());
        outboxMessageRepository.updateStatusAndErrorMsgByMessageId(messageId, MessageStatus.FAILED.getValue(),
                String.format(ERROR_MES_TEMPLATE, returned.getReplyCode(), returned.getReplyText()), LocalDateTime.now());
    }
}
